#include "EchoServer.h"
#include <iostream>
#include <functional>
using std::bind;
using std::cout;
using std::endl;
using namespace  std::placeholders;


class MyTask
{
public:
    MyTask(const TcpConnectionPtr &con, const string &msg)
        : _con(con),
          _msg(msg)
    {
    }
    void process()
    {
        _con->sendInLoop("hello  "+_msg);
    }
private:
    TcpConnectionPtr _con;
    string _msg;
};

EchoServer::EchoServer(const string &ip, unsigned short port, size_t threadNum, size_t queueSize)
:_server(ip,port),
_pool(threadNum,queueSize)
{
}

EchoServer::~EchoServer(){

}

void EchoServer::start(){
    _pool.start();
    _server.setAllCallback(bind(&EchoServer::newConnectionCB,this,_1),
    bind(&EchoServer::MessageCB,this,_1),
    bind(&EchoServer::CloseCB,this,_1));
    _server.start();
}

void EchoServer::stop(){
    _pool.stop();
    _server.stop();
}

void EchoServer::newConnectionCB(const TcpConnectionPtr &con)
{
    cout << con->toString() << " has connected! " << endl;
}

void EchoServer::CloseCB(const TcpConnectionPtr &con)
{
    cout << con->toString() << " has disconnected! " << endl;
}

void EchoServer::MessageCB(const TcpConnectionPtr &con)
{
    string msg = con->receive();
    MyTask t(con, msg);
    _pool.addTask(bind(&MyTask::process, &t));
}

